/**
 * 将平面数组转换成树形结构的方法
 * @function transformArrayToTreeFormat
 * @param {object} setting - 配置项
 * 	setting = {
 *		idKey:'',
 *		pIdKey:'',
 *		childrenKey:''
 *	}
 * @param {Array} sNodes - 数据数组
 * @example
 *   let list = [{id:'1',pid:'0',name:'1'},{id:'2',pid:'1',name:'1-1'}];
 *   let tree = TreeUtil.transformArrayToTreeFormat({
 *   	idKey:'id',
 *   	pIdKey:'pid',
 *   	childrenKey:'children'
 *   },list);
 *
 *   返回的tree格式为：
 *   {
 *   	id:'1',
 *   	name:'1',
 *   	children:[{
 *   		id:'2',
 *   		name:'1-1',
 *   	}]
 *   }
 */
export function transformArrayToTreeFormat(setting, sNodes) {
  let i,
    l,
    key = setting.idKey,
    parentKey = setting.pIdKey,
    childKey = setting.childrenKey
  if (!key || key == '' || !sNodes) return []

  if (Array.isArray(sNodes)) {
    let r = []
    let tmpMap = []
    for (i = 0, l = sNodes.length; i < l; i++) {
      tmpMap[sNodes[i][key]] = sNodes[i]
    }
    for (i = 0, l = sNodes.length; i < l; i++) {
      if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) {
        if (!tmpMap[sNodes[i][parentKey]][childKey]) tmpMap[sNodes[i][parentKey]][childKey] = []
        tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i])
      } else {
        r.push(sNodes[i])
      }
    }
    return r
  } else {
    return [sNodes]
  }
}

/**
 * 树转数组
 * @param {*} treeData
 * @param {*} childrenName
 */
export function transformTreeToArrayFormat(treeData, childrenName) {
  let newList = []
  function findChildren(node) {
    let children = node[childrenName]
    if (children) {
      for (let i = 0; i < children.length; i++) {
        let childNode = children[i]
        findChildren(childNode)
        newList.push(childNode)
      }
    }
  }
  for (let i = 0; i < treeData.length; i++) {
    let node = treeData[i]
    findChildren(node)
    newList.push(node)
  }
  return newList
}
